package parallels.servertech.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

public class CommandProcessor {
	private final BufferedReader in;
	private final PrintStream out;
	private final Map<String, CommandHandler> handlers = new HashMap<>();
	private final CommandContext ctx;
	
	public CommandProcessor(InputStream in, PrintStream out) throws IOException {
		this.in = new BufferedReader(new InputStreamReader(in, "UTF-8"));
		this.out = out;
		ctx = new DefaultCommandContext(out);
	}

	public void addHandler(String command, CommandHandler handler) {
		handlers.put(command, handler);
	}

	public void handle() throws IOException {
		System.out.print("> ");
		String cmd = in.readLine().trim();
		
		if (cmd.isEmpty()) {
			return;
		}
		
		String[] cmdWithArgs = cmd.split("\\s+", 2);
		String command = cmdWithArgs[0];
		CommandHandler handler = handlers.get(command);
		String[] args = {};
		if (cmdWithArgs.length > 1) {
			args = cmdWithArgs[1].split("\\s+");
		}
		
		if (handler == null) {
			out.printf("unknown command: %s%n", command);
			return;
		}
		
		handler.handle(args, ctx);
	}
}
